<?php

namespace App\Admin\Actions\ProductBatch;

use App\Models\CustomerModel;
use App\Models\ProductsBatchModel;
use App\Models\ProductsSaleModel;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class MarketSale extends RowAction
{
    public $name = '入市销售';

    public function handle(ProductsBatchModel $model)
    {
        $data = request()->post();

        DB::beginTransaction();

        /** @var ProductsBatchModel $batch */
        $batch = ProductsBatchModel::where('batch_id', $this->getKey())
            ->lockForUpdate()
            ->first();

        if ($batch['stock'] < $data['sale_num']) {
            DB::rollBack();
            return $this->response()->error('库存不足');
        }

        $batch['sale_number'] += $data['sale_num'];

        $batch->save();

        $sale = new ProductsSaleModel();

        $sale['batch_id']    = $this->getKey();
        $sale['sale_num']    = $data['sale_num'];
        $sale['customer_id'] = $data['customer_id'];
        $sale['code']        = ProductsSaleModel::createSourceCode();
        $sale['sale_type']   = 2;

        $sale->save();

        DB::commit();

        return $sale ? $this->response()->success('入市成功')->refresh() : $this->response()->error('入市失败');
    }

    public function form(ProductsBatchModel $model)
    {
        $this->select('customer_id', '选择客户')->options(function ($name) {
            return CustomerModel::pluck('name', 'customer_id')->toArray();
        })->required();
        $this->text('sale_num', $model['product']['product_name'])->placeholder('数量')
            ->required();
    }
}
